#!/usr/bin/bash
##############################################################
# License Terms
# 
# "This software" is SimpleSMF, or sometimes spelled simplesmf, presently available from http://code.google.com/p/simplesmf
# 
# Copyright (c) 2012 CleverTrove, LLC
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
##############################################################
#
MAXCOUNT=6    # How many times to retry any pools that fail to import/export
DELAY=5       # How long to delay between retries
CONF=/etc/simplesmf-iscsi-zpool.conf
PATH=/usr/gnu/bin:/usr/bin:/usr/sbin:/sbin
#
#
# Don't edit below this line
#
#
if [ "$1" = "import" ] ; then
  COUNT=0
  FAILED=
  POOLS=`cat $CONF | sed 's/#.*//'`
  while [ "$COUNT" -lt "$MAXCOUNT" -a -n "$POOLS" ] ; do
    for POOL in $POOLS ; do
      if ( ! zpool list $POOL &> /dev/null ) ; then # check to see if it's already imported, before attempting to import
        zpool import -c /etc/zfs/simplesmf-iscsi-zpool.cache $POOL
      fi
      if ( ! zpool list $POOL &> /dev/null ) ; then # then it failed to import
        FAILED="$FAILED $POOL"
      fi
    done
    if [ -z "$FAILED" ] ; then
      exit 0
    else
      POOLS=$FAILED
      FAILED=
      sleep $DELAY
    fi
    $COUNT=$(($COUNT + 1))
  done
  exit 1
elif [ "$1" = "export" ] ; then
  COUNT=0
  FAILED=
  POOLS=`cat $CONF | sed 's/#.*//'`
  while [ "$COUNT" -lt "$MAXCOUNT" -a -n "$POOLS" ] ; do
    for POOL in $POOLS ; do
      if ( zpool list $POOL &> /dev/null ) ; then # check to see if it's imported, before attempting to export
        zpool export $POOL
      fi
      if ( zpool list $POOL &> /dev/null ) ; then # then it failed to export
        FAILED="$FAILED $POOL"
      fi
    done
    if [ -z "$FAILED" ] ; then
      exit 0
    else
      POOLS=$FAILED
      FAILED=
      sleep $DELAY
    fi
    $COUNT=$(($COUNT + 1))
  done
  exit 1
else
  echo "Usage:  Specify 'import' or 'export'"
  echo "Will read $CONF for a list of pools"
fi
